package com.ogawa.chair7808.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.content.*
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import cn.ljuns.logcollector.LogCollector
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.easepal.softaplib.wifi.WiFiManager
import com.example.reslib.utils.PreferenceWrapper
import com.example.reslib.utils.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.Constant.*
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_CONNECT_MQTT
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_HOME_POWER
import com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_MQTT_CONNECT_STATE
import com.ogawa.base.Constant.MqttConstant.MQTT_STATE_UNCONNECT
import com.ogawa.base.callback.GetOnlineCallback
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.network.BaseResponse
import com.ogawa.base.network.bean.BeanOnline
import com.ogawa.base.utils.CommonUtil
import com.ogawa.base.utils.DebugUtils
import com.ogawa.base.utils.NetUtil
import com.ogawa.base.utils.StringUtils
import com.ogawa.base.utils.util.MiuiUtils
import com.ogawa.base.utils.util.OSUtils
import com.ogawa.chair7808.R
import com.ogawa.chair7808.bean.TempDevice7808StateBean
import com.ogawa.chair7808.cache.*
import com.ogawa.chair7808.interfaces.OnAutoFinish
import com.ogawa.chair7808.manager.DataManager
import com.ogawa.chair7808.manager.DataManager.Companion.creatFile
import com.ogawa.chair7808.manager.DataManager.Companion.dataManager
import com.ogawa.chair7808.observer.SoftApSucceedObserver
import com.ogawa.chair7808.utils.Activity7808Utils
import com.ogawa.chair7808.viewmodel.HomeActivityViewModel
import com.ogawa.networklib.RetrofitManager
import com.ogawa.networklib.RxObserver
import com.ogawa.networklib.networkBean.BaseResponseBean
import com.ogawa.networklib.networkBean.MqttAccountBean
import com.ogawa.widget.DataShowPopWindow
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import kotlin.system.exitProcess

/**
 * 首页
 */
@Route(path = UrlPathConstant.ACTIVITY_7808_MAIN)
class Home7808Activity7808 : BaseMqtt7808Activity(), View.OnClickListener,
//        IHomeView7506,
        SoftApSucceedObserver.onSoftApLis {
    private var isExit = false

    //    private var mPresenter: HomePresenter7506? = null
    private var mLlAuto: LinearLayout? = null
    private var mLlHand: LinearLayout? = null
    private var mLlAtti: LinearLayout? = null
    private var isFirst = true
    private var mTvNoNet: TextView? = null
    private var mIvWifi: ImageView? = null
    private var mRlRunning: RelativeLayout? = null
    private var mTvRunning: TextView? = null
    private var intentFilter: IntentFilter? = null
    private var mDisposable: Disposable? = null
    private var mCount = 0
    private var mRunning = 0 //1 专业按摩  2 高级按摩
    private var mAutoName: String? = null
    private var mSp: PreferenceWrapper? = null
    private var mSaveVersion = ""
    private var mSaveCount = 0

    private var viewModel: HomeActivityViewModel? = null
    override fun initTitleBar() {
        super.initTitleBar()
        titleBar.setTitleNameGone()
        titleBar.setBackGone()
        titleBar.showWifi()
    }

    override fun initView(layoutId: Int) {
        super.initView(layoutId)
        LiveEventBus
                .config()
                .enableLogger(false)
//                .lifecycleObserverAlwaysActive(false)
//                .autoClear(true)

        viewModel = ViewModelProviders.of(this).get(HomeActivityViewModel::class.java)
//        viewModel!!.initMqtt(this)
        mSp = PreferenceWrapper()
        mSaveVersion = mSp!!.getStringValue(Constants.SAVE_VERSION, "")
        mSaveCount = mSp!!.getIntValue(Constants.SAVE_COUNT, 0)
        //测试
//        mSp!!.setStringValueAndCommit(Constant.KEY_SN_7808, "OG7516A2104080002")

        var curSn = mSp!!.getStringValue(Constant.KEY_SN_7808, "")
        mSn = curSn
        MqttManager.instance.curSn = curSn
        mLlAuto = findViewById(R.id.linear_attitude_adjustment)
        mLlHand = findViewById(R.id.linear_high_massage)
        mLlAtti = findViewById(R.id.linear_professional_massage_7506)
        mTvNoNet = findViewById(R.id.home_tv_nonet)
        mIvWifi = findViewById(R.id.title_wifi)
        mRlRunning = findViewById(R.id.home_rl_running)
        mTvRunning = findViewById(R.id.home_tv_running)
        mLlAtti?.setOnClickListener(this)
        mLlHand?.setOnClickListener(this)
        mLlAuto?.setOnClickListener(this)
        mIvWifi?.setOnClickListener(this)
        mRlRunning?.setOnClickListener(this)
//        mPresenter = HomePresenter7506(this)
        ////输出log
        if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
        }
        LogCollector.getInstance(application)
                .setCleanCache(true) //                .setTag("SendCommond7506","socket7506","TEST")
                .setTag("TEST")
                .setCacheFile(creatFile())
                .setCleanCache(true)
                .start()
        SoftApSucceedObserver.getInst().registerObserver(this) //监听是否配网成功
//        LiveEventBus.get(LIVE_EVENT_BUS_KEY_STATUS, Boolean::class.java).observe(this, {
//            mIvWifi?.isSelected = it
//            dataManager.isInitSucceed = it
//        })
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_CONNECT_MQTT, Int::class.java).observe(this, {
            loadData()
        })
        LiveEventBus.get(Constant.LIVE_EVENT_BUS_KEY_NET_STATE, Boolean::class.java).observe(this, {
            Log.e("HOME_NET", "$it====")
            if (!CommonUtil.isActivityTop(SoftApActivity::class.java, this@Home7808Activity7808)
                    && !CommonUtil.isActivityTop(SoftApOldActivity::class.java, this@Home7808Activity7808)
                    && !CommonUtil.ActivityTop(this@Home7808Activity7808).contains("WifiSettingsActivity")) {
                if (it) {
                    mTvNoNet!!.visibility = View.GONE
                    loadData()

                } else {
                    mTvNoNet!!.visibility = View.VISIBLE
                    MqttManager.instance.clearData()
                    LiveEventBus.get(LIVE_EVENT_BUS_KEY_MQTT_CONNECT_STATE).post(MQTT_STATE_UNCONNECT)
                }
            }

        })
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_HOME_POWER, Int::class.java).observe(this, {
            toSoftAp()
        })

        if(NetUtil.instance.hasNet()){
            mTvNoNet!!.visibility = View.GONE
        }
        else{
            mTvNoNet!!.visibility = View.VISIBLE
        }

    }

    override fun refreshIcon(isConnect: Boolean){
        Log.e("refreshIcon", "===$isConnect")
        mIvWifi?.isSelected = isConnect
        isInitSucceed = isConnect
        mRlRunning!!.visibility = View.GONE

    }

    fun showInfo(){
        Handler().postDelayed({
            try {
                var dataShowPopWindow = DataShowPopWindow(this)
                val layoutParams: WindowManager.LayoutParams = WindowManager.LayoutParams()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                } else {
                    layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                }
                layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT
                layoutParams.format = PixelFormat.RGBA_8888
                // 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
                // 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
                layoutParams.flags =  // LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE // LayoutParams.FLAG_NOT_TOUCHABLE

                layoutParams.gravity = Gravity.RIGHT or Gravity.TOP
//                dataShowPopWindow.wmParams = layoutParams
//                dataShowPopWindow.show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, 1000)
    }


    override fun changeTime(bean: TempDevice7808StateBean.FunctionsBean) {
        super.changeTime(bean)
        LogUtils.e("homeChangeTime==")



    }

    override fun changeViewByMqttMessage() {
        super.changeViewByMqttMessage()
        titleBar.initData()
        if (!hasProgramRunning) {
            mRlRunning!!.visibility = View.GONE
        } else {
            mRlRunning!!.visibility = View.VISIBLE
            if (isautoProgram) {
                val name = autoProgramName
                showRunning("正在执行专业按摩:$name", name)
            } else if (isHandProgram) {
                showRunning("正在执行高级按摩", "");
            } else {
                showRunning("", "");
            }

        }

    }

    override fun onResume() {
        super.onResume()
        MqttManager.instance.setIsSoftAp(false)

//        if (!MqttManager.getInstance().isConnect&&!TextUtils.isEmpty(dataManager.getmSn())) { //如果Mqtt未连接，则尝试连接
//            getOnline()
//        }
    }


    override fun loadData() {
        super.loadData()
        if (!TextUtils.isEmpty(mSn)) {
            getOnline()
            showloading()
        }
    }

    fun getOnline(){
        dataManager.getOnline(this, mSn, 0, object : GetOnlineCallback {
            override fun onGetOnlineSuccess(program: BaseResponse<BeanOnline>?) {

                getMqttAccount()
            }

            override fun onGetOnlineFailure() {
                cancleloading()
                if (CommonUtil.isActivityTop(Home7808Activity7808::class.java, this@Home7808Activity7808)) {
                    ToastUtils.showShortToast(this@Home7808Activity7808, "未检测到设备在线，请检查设备是否通电，或配网后使用")
                }
            }

        })

    }
    override fun setLayoutId(): Int {
        return R.layout.activity_main_7808
    }

    override fun onClick(v: View) {
        val i = v.id
        if(mSn.isNullOrEmpty()){
            if (CommonUtil.isFastClick()) {
                return
            }
            toSoftAp()
           return
        }

        if (i == R.id.linear_attitude_adjustment) {
            if (DebugUtils.isDebug) {
                Activity7808Utils.startAttitudeAdjustmentActivity(this)
                return
            }

            if (isOpen) {
                Activity7808Utils.startAttitudeAdjustmentActivity(this)
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        }
        else if (i == R.id.linear_professional_massage_7506) { //专业按摩
            if (DebugUtils.isDebug) {
                Activity7808Utils.startProfessionMassaActivity(this)
                return
            }
            if (isOpen) {
                Activity7808Utils.startProfessionMassaActivity(this)
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        }
        else if (i == R.id.linear_high_massage) { //高级按摩
            if (DebugUtils.isDebug) {
                Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
                return
            }
            if (isOpen) {
//                自动程序是否在运行
                if (!isautoProgram){
                    Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
                }else{
                    showNoticeDialog(object : OnAutoFinish {
                        override fun onAutoClose() {
                            stopAuto()
                        }
                    })
                }
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        }
        else if (i == R.id.title_wifi) {
            if (CommonUtil.isFastClick()) {
                return
            }
            toSoftAp()
        }
        else if (i == R.id.home_rl_running) {
            if (isPause) {
                dataManager.sendCommond(CommmandNum.PAUSE, "5")
            }
            Log.e("mRUNNING", "$mRunning====")
            if (mRunning == 1) {
                Activity7808Utils.startProMasDetailActivity(this, mAutoName)
            } else {
                Activity7808Utils.startAdvancedMassageActivity(this)
            }
        }
    }
    private fun toSoftAp(){
        if(!WiFiManager.getInstance(this).isWifiEnabled){
            ToastUtils.showShortToast(this, "请先打开wifi")
            return
        }
        if (CommonUtil.isOPenGPS(this)) {
            getPer()
        } else {
            ToastUtils.showShortToast(this, "配网需要使用定位权限，请先开启定位服务")
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click()
        }
        return false
    }

    private fun stopAuto() {
        dataManager.sendCommond(CommmandNum.FINISH, "4")
        showloading()
        GlobalScope.launch{
            var isSuccess = false
            delay(3000)
            for (time in 0..10){
                delay(1000)
                val value = StringUtils.getValue(deviceStatusBean.runningStatusQuery)
                if (value != 4){
                    isSuccess = true
                    break
                }
            }
            launch(Dispatchers.Main){
                cancleloading()
            }
            if (isSuccess){
                Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
            }
        }
    }

    /**
     * 双击退出
     */
    private fun exitBy2Click() {
        var tExit: Timer?
        if (!isExit) {
            isExit = true
            // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000)
        } else {
            exitProcess(0)
        }
    }


    override fun onPermissionSuccess() {
        super.onPermissionSuccess()
        if (OSUtils.isMiui()) {
            val stratTime = System.currentTimeMillis()
            val mWifiManager = this.applicationContext
                    .getSystemService(WIFI_SERVICE) as WifiManager
            val disconnect = mWifiManager.disconnect()
            val endTime = System.currentTimeMillis()
            if (endTime - stratTime > 200 || !disconnect) {
                AlertDialog.Builder(this)
                        .setTitle("请设置权限")
                        .setMessage("请开启WLAN权限，设置为始终运行，以便后续操作")
                        .setNegativeButton(R.string.cancle) { dialog, _ -> dialog.dismiss() }
                        .setPositiveButton(R.string.confirm) { dialog, _ ->
                            dialog.dismiss()
                            MiuiUtils.jumpToPermissionsEditorActivity(this@Home7808Activity7808)
                        }
                        .show()
            }
            else{
                Activity7808Utils.startSoftApActivity(this)
            }
        } else {
            Activity7808Utils.startSoftApActivity(this)
        }
    }



    fun showRunning(show: String, name: String) {
        if (TextUtils.isEmpty(show)) {
            mRunning = 0
            mRlRunning!!.visibility = View.GONE
        } else {
            if (TextUtils.isEmpty(name)) {
                mRunning = 2
            } else {
                mAutoName = name
                mRunning = 1
            }
            mRlRunning!!.visibility = View.VISIBLE
            mTvRunning!!.text = show
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        isConnectSocket = false
        MqttManager.instance.clearData()

//        mPresenter!!.onDestory()
    }

    //wifi 配置成功
    override fun isSoftApOk() {
        MqttManager.instance.setIsSoftAp(false)
       getMqttAccount()
    }


    var mqttAccount: String? = null
    var mqttPsw: String? = null

    /**
     * 获取Mqtt账号密码
     */
    fun getMqttAccount() {
        var curSn = PreferenceWrapper().getStringValue(Constant.KEY_SN_7808, "")
        val instance = RetrofitManager.getInstance()
        if (TextUtils.isEmpty(curSn)) {
            return
        }
        onShowLoading()
        instance.getData(instance.apiService.getMqttAccount(curSn) //"OGA75172004080001"
                , object : RxObserver<BaseResponseBean<MqttAccountBean?>?>(this, true) {
            override fun onSuccess(responseBean: BaseResponseBean<MqttAccountBean?>?) {
                mqttAccount = responseBean?.data?.username
                mqttPsw = responseBean?.data?.password
                connectMqtt(true)
            }

            override fun onError(errMsg: String) {
//                canclekProgress()
            }

        }, this)
    }

    private fun connectMqtt(isInit: Boolean) {
        if (TextUtils.isEmpty(mqttAccount) || TextUtils.isEmpty(mqttPsw)) {
            if (!isInit) {
                ToastUtils.showShortToast(this, "暂无设备信息，请通过网络配置获取设备信息")
            }
            return
        }

            MqttManager.instance.setMqttMsg(mqttAccount, mqttPsw)
            MqttManager.instance.buildClient()

    }



    private fun chekcUpData() {
        Handler().post {
            //如果进入应用时没检查 则再检查一次更新
//            if (null == getInst().getmUpdataBean()) {
            //检查网络更新
//                CommondManager.getInst().getUpdata(this@Home7808Activity7808, object : GetUpdataCallback {
//                    override fun onGetOnlineSuccess(program: BaseResponse<BeanUpdata>) {
//                        Log.e("checkUpdata", "checkUpdata_succeed")
//                        getInst().isHasCheckUpdataOk = true
//                        val bean = program.data
//                        if (bean.isupgrade == 1) {
//                            if (bean.isforce == 1) {
//                                mSp!!.setStringValueAndCommit(Constants.SAVE_VERSION, bean.appversion)
//                                mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, 0)
//                                doUpdata(bean)
//                            } else {
//                                if (mSaveVersion != bean.appversion) {
//                                    mSp!!.setStringValueAndCommit(Constants.SAVE_VERSION, bean.appversion)
//                                    mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, 1)
//                                    doUpdata(bean)
//                                } else if (mSaveCount <= 3) {
//                                    mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, mSaveCount + 1)
//                                    doUpdata(bean)
//                                }
//                            }
//                        }
//                    }
//
//                    override fun onGetOnlineFailure() {
//                        getInst().isHasCheckUpdataOk = false
//                        Log.e("checkUpdata", "checkUpdata_onGetOnlineFailure")
//                    }
//                })
//            }
        }
    }
//    private fun setNetListener() {
//        var request = NetworkRequest.Builder().build()
//        var connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//        connMgr.registerNetworkCallback(request, NetUtil.instance)
//    }

}